<template>
  <div id="apiModeCode" class="w-full h-340" style="overflow: auto"></div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue';

import { EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { defaultKeymap } from '@codemirror/commands';
import { getModelTemplate } from '@/api/decision-engine';
import type { IGetModelTemplateReq, IGetModelTemplateRes } from '@/api/decision-engine';

const emit = defineEmits<{
  (e: 'mountedFinish'): void;
}>();
let startState = EditorState.create({
  doc: '',
  extensions: [keymap.of(defaultKeymap)]
});

let view: any;

onMounted(() => {
  emit('mountedFinish');
  view = new EditorView({
    state: startState,
    parent: document.getElementById('apiModeCode') as Element // document.body
  });
});

// const props = defineProps<{
//   conjValue: any;
// }>();
// const emit = defineEmits(['newValue']);

// const value = ref();
// value.value = props.conjValue;

// const options = ref<DictDTO[]>([]);
const templateID = ref('');

// 初始化
const initData = async (id: any) => {
  templateID.value = id;
  dictRequest();
};

const getData = () => {
  return { code: view.state.doc.toString() };
};

// 模板
const dictRequest = async () => {
  const params: IGetModelTemplateReq = {
    templateName: templateID.value
  };
  const data: IGetModelTemplateRes = await getModelTemplate(params);
  if (data) {
    // (Assume view is an EditorView instance holding the document "123".)
    let transaction = view.state.update({ changes: { from: 0, insert: data } });
    // At this point the view still shows the old state.
    view.dispatch(transaction);
    // And now it shows the new state.
  }
};

defineExpose({
  initData,
  getData
});
</script>
